import React, { FC, useState } from 'react';
import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import { Button, Modal, ConfigProvider, Dropdown, Space, Tag, theme } from 'antd';
import { useRef } from 'react';
import type { TableColumnsType, TableProps } from 'antd';
// import { businessFinanceIndexList } from 'api/businessFinance/service';
import { businessFinanceIndexList } from '../../../../api/businessFinance/service';
const columns: ProColumns<businessFinanceIndexListTableData>[] = [
  {
    dataIndex: 'index',
    valueType: 'indexBorder',
    width: 60,
    title: '序号',
  },
  {
    title: '发票单据号',
    dataIndex: 'invoiceNo',
    copyable: true,
    ellipsis: true,
    sorter: true,
    search: true,
    fieldProps: {
      placeholder: '请输入发票单据号',
    },
  },
  {
    title: '流程状态',
    dataIndex: 'processStatus',
    valueType: 'select',
    filters: true,
    onFilter: true,
    ellipsis: true,
    fieldProps: {
      options: [
        { label: '待处理', value: 'pending', status: 'Warning' },
        { label: '处理中', value: 'processing', status: 'Processing' },
        { label: '已完成', value: 'completed', status: 'Success' },
        { label: '已驳回', value: 'rejected', status: 'Error' },
      ],
    },
  },
  {
    title: '经办人',
    dataIndex: 'operator',
    ellipsis: true,
    search: true,
    fieldProps: {
      placeholder: '请输入经办人',
    },
  },
  {
    title: '经办日期',
    dataIndex: 'operateDate',
    valueType: 'date',
    sorter: true,
    hideInSearch: true,
  },
  {
    title: '经办日期',
    dataIndex: 'operateDate',
    valueType: 'dateRange',
    hideInTable: true,
    // 关键：确保 search 始终是对象（需要转换时）或 undefined（禁用时）
    search: {
      transform: (value) => ({
        operateStartTime: value?.[0],
        operateEndTime: value?.[1],
      }),
    },
    // 避免条件判断导致的错误（如需要动态禁用，用 undefined 而非 false）
    // 错误示例：search: shouldShow ? { transform: ... } : false → 会导致传入 false
    // 正确示例：search: shouldShow ? { transform: ... } : undefined → 禁用时不传递
    fieldProps: {
      rangeConfig: {
        placeholder: ['开始日期', '结束日期'],
      },
    },
  },
  {
    title: '经办部门',
    dataIndex: 'operateDept',
    ellipsis: true,
    filters: true,
    onFilter: true,
  },
  {
    title: '开票类型',
    dataIndex: 'invoiceType',
    valueType: 'select',
    filters: true,
    onFilter: true,
    fieldProps: {
      options: [
        { key: 1, label: 'æå', value: 'normal' },
        { key: 2, label: 'é¢å', value: 'special' },
      ],
    },
  },
  {
    title: '客户名称',
    dataIndex: 'customerName',
    ellipsis: true,
    fieldProps: {
      placeholder: '请输入客户名称',

    },
  },
  {
    title: '本次开票总金额（含税）',
    dataIndex: 'totalAmountWithTax',
    valueType: 'money',
    sorter: true,
     search: false,
    fieldProps: {
     
      precision: 2,
    },
  },
  {
    title: '本次开票总金额（不含税）',
    dataIndex: 'totalAmountWithoutTax',
    valueType: 'money',
    sorter: true,
          search: false,
    fieldProps: {

      precision: 2,
    },
  },
  {
    title: '本次开票税额',
    dataIndex: 'taxAmount',
    valueType: 'money',
    sorter: true, search: false,
    fieldProps: {
      precision: 2,
    },
  },
  {
    title: '发票类型',
    dataIndex: 'invoiceCategory',
    valueType: 'select',
    filters: true,
    onFilter: true,
    fieldProps: {
      options: [
        { key: 1, label: '增值税专用发票', value: 'vat' },
        { key: 1, label: '普通发票', value: 'ordinary' },
      ],
    },
  },
  {
    title: '发票代码',
    dataIndex: 'invoiceCode',
    copyable: true,
    ellipsis: true,
  },
  {
    title: '开具日期',
    dataIndex: 'issueDate',
    valueType: 'date',

  },
  {
    title: '过账日期',
    dataIndex: 'postingDate',
    valueType: 'date',
    sorter: true,
  },
  {
    title: 'SAP凭证号',
    dataIndex: 'sapVoucherNo',
    ellipsis: true,  // 超出长度 显示省略号
    search: true,
    fieldProps: {
      placeholder: 'SAP凭证号', // 正确位置
    },
  },
  {
    title: '开票总金额（含税）',
    dataIndex: 'totalInvoicedWithTax',
    valueType: 'money',
    search: false,
    fieldProps: {
      placeholder: '开票总金额（含税）',
      precision: 2,
    },
  },
  {
    title: '开票总金额（不含税）',
    dataIndex: 'totalInvoicedWithoutTax',
    valueType: 'money',
    search: false,
    fieldProps: {
      placeholder: '开票总金额（不含税）',
      precision: 2,
    },
  },
  {
    title: '总税额',
    dataIndex: 'totalTax',
    valueType: 'money',
    search: false,
    sorter: false,
    fieldProps: {
      precision: 2,
    },
  },
  {
    title: '专业类型',
    dataIndex: 'professionalType',
    ellipsis: true,
    filters: true,
    onFilter: true,

    valueType: 'select',
    fieldProps: {
      options: [
        { key: 1, label: '金融服务', value: 'financialService' },
        { key: 2, label: '信息技术', value: 'informationTechnology' },
        { key: 3, label: '咨询服务', value: 'consultingService' },
        { key: 4, label: '贸易零售', value: 'tradeRetail' },
        { key: 5, label: '制造业', value: 'manufacturing' },
        { key: 6, label: '建筑业', value: 'construction' },
        { key: 7, label: '医疗健康', value: 'healthcare' },
        { key: 8, label: '教育培训', value: 'educationTraining' },
        { key: 9, label: '文化传媒', value: 'cultureMedia' },
        { key: 12, label: '物流运输', value: 'logisticsTransport' },
        { key: 19, label: '房地产', value: 'realEstate' },
        { key: 10, label: '其他', value: 'other' },
      ],
    },
  },
  {
    title: '已核销金额',
    dataIndex: 'writtenOffAmount',
    valueType: 'money',
    search: false,
    fieldProps: {
      precision: 2,
    },
  },
  {
    title: '未核销金额',
    dataIndex: 'unwrittenOffAmount',
    valueType: 'money',
    search: false,
    fieldProps: {
      precision: 2,
    },
  },
  {
    title: '开票单位抬头',
    dataIndex: 'invoiceUnit',
    ellipsis: true,
    search: false,
    fieldProps: {
      placeholder: '请输入开票单位',
      precision: 2,
    },
  },
  {


    title: '销售类型',
    dataIndex: 'salesType',
    ellipsis: true,
    filters: true,
    onFilter: true,
    valueType: 'select',
    fieldProps: {
      options: [
        { label: '普通销售', value: 'ordinarySales' },
        { label: '批发销售', value: 'wholesaleSales' },
        { label: '零售销售', value: 'retailSales' },
        { label: '代销', value: 'consignmentSales' },
        { label: '分销', value: 'distributionSales' },
        { label: '团购', value: 'groupPurchase' },
        { label: '促销活动', value: 'promotionSales' },
        { label: '定制销售', value: 'customizedSales' },
        { label: '服务销售', value: 'serviceSales' },
        { label: '线上销售', value: 'onlineSales' },
        { label: '线下销售', value: 'offlineSales' },
        { label: '其他', value: 'other' },
      ],
    },
  },

  {
    title: '操作',
    valueType: 'option',
    key: 'option',
    render: (text, record, _, action) => [
      // <a
      //     key="editable"
      //     onClick={() => {
      //         action?.startEditable?.(record.id);
      //     }}
      // >
      //     编辑
      // </a>,
      // <a href={record.url} target="_blank" rel="noopener noreferrer" key="view">
      //     查看
      // </a>,
      <TableDropdown
        key="actionGroup"
        onSelect={() => action?.reload()}
        menus={[
          { key: 'copy', name: '复制' },
          { key: 'delete', name: '删除' },
        ]}
      />,
    ],
  },
];

const businessFinanceList: FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modealSelectedRows, setmodealSelectedRows] = useState<businessFinanceIndexListTableData[]>([]);
  const actionRef = useRef<ActionType>(null);

  const themeConfig = {
    token: {

      borderRadius: 4,
      // 选中行背景色
      colorBgSelected: '#e6f7ff', // 浅蓝色示例
      // 选中行hover背景色
      colorBgSelectedHover: '#d1eaff',
    },
    algorithm: [theme.compactAlgorithm],
  };
  const showModal = () => {
    setIsModalOpen(true);
  };



  // 请求数据
  const fetchData = async (
    params: InvoiceInformationModealForm,
    sort: Record<string, 'ascend' | 'descend' | null>,
    filter: Record<string, (string | number)[] | null>) => {
    const response = await businessFinanceIndexList(params);
    return {
      data: response.list || [],
      total: response.total || 0,
      success: true,
    };
  }

  // 选择行 配置回调
  const rowSelection: TableProps<businessFinanceIndexListTableData>['rowSelection'] = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: businessFinanceIndexListTableData[]) => {
      console.log(`当前选中: ${selectedRowKeys}`, '所以选中: ', selectedRows);
      setmodealSelectedRows(selectedRows);
    },
    // 为每一行配置复选框属性 （禁用 / 启用） （默认选中 / 不选中） 为复选框添加额外属性（如 disabled、checked 等）
    getCheckboxProps: (record: businessFinanceIndexListTableData) => ({

    }),
  };
  return (
    <>

      <ConfigProvider >
        <ProTable<businessFinanceIndexListTableData>
          columns={columns}
          rowSelection={{ type: 'checkbox', ...rowSelection }}
          actionRef={actionRef}
          cardBordered
          request={fetchData}
          editable={{
            type: 'multiple',
          }}
          columnsState={{
            persistenceKey: 'pro-table-singe-demos',
            persistenceType: 'localStorage',
            onChange(value) {
              console.log('value: ', value);
            },
          }}
          rowKey="id"
          search={{
            labelWidth: 'auto',
          }}
          options={{
            setting: {
              listsHeight: 400,
            },
          }}
          form={{
            // 由于配置了 transform，提交的参数与定义的不同这里需要转化一下
            syncToUrl: (values, type) => {
              if (type === 'get') {
                return {
                  ...values,
                  created_at: [values.startTime, values.endTime],
                };
              }
              return values;
            },
          }}
          pagination={{
            pageSize: 5,
            onChange: (page) => console.log(page),
          }}
          dateFormatter="string"
          headerTitle="发票信息"
          scroll={{ x: 'max-content' }}
          toolBarRender={() => [
          ]}
        />
      </ConfigProvider>

    </>
  );
}
// 设置组件显示名称，便于调试
businessFinanceList.displayName = 'businessFinanceList';
export default businessFinanceList;